const app = getApp();

// pages/index/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用来提示用户是否授权登录的信息
    title: "为了给你提供更好的服务，用户隐私保护提示",
    desc1: "感谢您使用营赢的，您使用前应当阅同意",
    urlTitle: "《用户隐私保护指引》",
    desc2: "当您点击同意并开始时用产品服务时，即表示你已理解并同息该条款内容，该条款将对您产生法律约束力。如您拒绝，将无法提供需要的服务",
    innerShow: true,
    height: 0,

    isUserProfileObtained: false, // 添加状态变量
    tapMe1: false,
    isSearch: true,
    isCear: false,
    imgList: [],
    val: '',
    carousels: '',
    img1: '',
    img2: '',
    img3: '',
    img4: '',
    //定义数组用来存放数据
    list: '',
    Search_del: false,
    popupBottom: -200, // 弹出窗口初始位置（负值表示隐藏在页面底部）
    popupHeight: 0, // 弹出窗口初始高度（0表示隐藏）
    userInfo: {
      avatarUrl: "",
      nickName: ""
    },
    showLoginButton: true, // 控制登录按钮显示与隐藏的变量
    canIUse: wx.canIUse('button.open-chooseAvatar.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.chooseAvatar.userAvatarUrl') && wx.canIUse('open-data.chooseAvatar.userAvatarUr'),
    showPopup: false, //弹窗
    checked: false, // 勾选框初始状态
    shops: [],
    selectedShop: null, // 存储选中的店铺名字
    //公告栏
  },
  // 轮播图触发事件
  getInputs: function (e) {
    var eventId = e.target.id;
    var carouselsList = this.data.carouselsList;
    var dataItem = {};
    for (var i = 0; i < carouselsList.length; i++) {
      if (eventId == carouselsList[i].id) {
        dataItem = carouselsList[i];
        break;
      }
    }
    console.info(dataItem);
    var reqUrl = '';
    if (dataItem.typeNumber == 2) {
      reqUrl = '/pages/category/category?value=' + dataItem.productIds + '&value2=' + dataItem.storeId;
      dataItem.value2 = dataItem.storeId;
      dataItem.value = 0
    } else {
      reqUrl = '/pages/article/article?contentArticle=' + dataItem.contentArticle + '&headline=' + dataItem.headline
    }
    wx.navigateTo({
      url: reqUrl,
      // 目标
      data: dataItem
      // 页面的路径，前面要加上 '/'
    });
  },
  // 公告内容
  getbulletinBoard: function () {
    wx.navigateTo({
      url: '/pages/bulletinBoard/bulletinBoard'
    });
  },


  // 阴影点击关闭弹窗事件
  closePopup: function () {
    this.setData({
      showPopup: false
    });
  },
  //勾选店铺
  radioChange: function (e) {
    console.log("触发勾选了")
    const value = e.detail.value;
    const shops = this.data.shops.map(shop => {
      shop.checked = shop.name === value;
      return shop;
    });
    this.setData({
      shops: shops,
      selectedShop: shops.find(shop => shop.checked), // 更新选中的店铺信息,
      checked: true
    });
  },
  // 按钮提交
  submitForm: function () {
    const selectedShop = this.data.selectedShop;
    console.log("点击了")
    console.log(selectedShop);
    if (this.data.checked) {
      // 执行提交操作
      console.log('提交成功');
      // 关闭弹窗
      this.closePopup();
      wx.openLocation({
        latitude: selectedShop.latitude, //维度
        longitude: selectedShop.longitude, //经度
        name: selectedShop.name, //目的地定位名称
        scale: 15, //缩放比例
        address: selectedShop.address //导航详细地址
      });
    } else {
      // 提示用户需要勾选才能提交
      wx.showToast({
        title: '请先勾选同意',
        icon: 'none'
      });
    }
  },

  // 弹窗事件页面
  showPopup: function () {
    var that = this;
    wx.request({
      url: `https://199shq.com/api/wxStore/getShop`, //备注带data这里不需要${addressId} https://199shq.com
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data); // 处理返回的数据
        const newData = res.data.data;
        console.log(newData); // 处理返回的数据
        that.setData({
          shops: newData,
          checked: false
        });

        console.log(that.data.shops); // 输出存入的数据
      },
      fail: function (error) {
        console.log(error); // 请求失败的处理
      }
    });
    this.setData({
      showPopup: true
    });




  },
  stopPropagation: function () {
    // 阻止事件冒泡，避免触发父元素的点击事件
  },

  preventDefault: function () {
    // 阻止默认点击事件，避免关闭弹窗
  },

  //-----------------------------------------------------
  // 加载判断临时会员是否已过期
  getProvisionalMember() {
    const userInfo = wx.getStorageSync('userInfo');
    console.log(userInfo.wxUserId);
    let currentDate = new Date();
    // 格式化日期时间为 "yyyy-MM-dd HH:mm:ss"
    var year = currentDate.getFullYear();
    var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
    var day = ('0' + currentDate.getDate()).slice(-2);
    var hours = ('0' + currentDate.getHours()).slice(-2);
    var minutes = ('0' + currentDate.getMinutes()).slice(-2);
    var seconds = ('0' + currentDate.getSeconds()).slice(-2);

    var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
    wx.request({
      url: `https://199shq.com/api/members/getProvisionalMember`, //199shq.com
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        userId: userInfo.wxUserId,
        endDate: formattedDate
      },
      success: function (res) {
        console.log(res.data.msg)
      },
      fail: function (error) {
        console.log(error);
      }
    })
  },


  // 路由跳转回来的时候查询当前是否已登录
  onRouteDone: function () {
    console.log('路由跳转完成');
    // 这里可以执行路由跳转完成后的操作
    // 查询缓存是否已登录
    const isLoggedIn = wx.getStorageSync('userInfo');
    console.log("查询缓存是否已登录:" + isLoggedIn)
    if (isLoggedIn) {
      console.log('已登录');
      this.getProvisionalMember(); // 查询会员是否已过期
      // 执行已登录后的操作
      this.setData({
        innerShow: false
      })

    }
  },

  // 用户隐私保护指引，跳转小程序的api
  openPrivacyContract() {
    wx.openPrivacyContract({
      success: res => {
        console.log('openPrivacyContract success')
      },
      fail: res => {
        console.error('openPrivacyContract fail', res)
      }
    })
  },



  // 隐藏弹出窗口
  // hidePopup() {
  //   
  //   this.setData({
  //     popupBottom: -200,
  //     popupHeight: 0
  //   });
  // },

  onChooseAvatar: function (res) { // 将当前获取到的用户真实的头像保存在本地缓存
    // 判断是否已授权获取用户信息
    if (!this.data.isUserProfileObtained) {
      wx.showToast({
        title: '请先完成授权',
        icon: 'none',
      });
      return;
    }

    const { // 将缓存的头像保存到本地
      userInfo
    } = this.data;
    userInfo.avatarUrl = res.detail.avatarUrl;
    console.log(res.detail.avatarUrl);
    this.setData({
      userInfo: userInfo
    });
    app.userInfo.avatarUrl = res.detail.avatarUrl;
    var filePath = getApp().userInfo.avatarUrl;
    console.log('头像路径filePath:', filePath);
    var fileName = Math.random().toString(36).substr(2);
    console.log('头像图片文件名fileName:', fileName);
    wx.setStorageSync('userInfo', this.data.userInfo); // 保存头像信息到本地缓存
    console.log("缓存头像临时Url:", wx.getStorageSync('userInfo'));


  },

  //登录方法
  bindGetUserInfo(e) {
    let that = this;
    // let token = wx.getStorageSync('token');



    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        that.setData({
          userInfo: res.userInfo,
          innerShow: false
        });
        console.log("res.userInfo的数据：" + res.userInfo)
        wx.showLoading({
          title: '加载中',
        });
        if (res.errMsg === "getUserProfile:ok") {
          let code = null;
          wx.login({
            success: function (e) {
              code = e.code;
              let params = {};
              params.code = code;
              params.avatarUrl = res.userInfo.avatarUrl;
              params.nickName = res.userInfo.nickName;
              params.gender = res.userInfo.gender;
              console.log("我的 同意登录之后的对象信息111" + params)
              wx.request({
                url: 'https://199shq.com/api/wxuser/login', // https://199shq.com
                data: params,
                method: 'POST',
                header: {
                  'Content-Type': 'application/json',
                },

                success: function (res) {
                  console.log(res.data.wxToken);
                  if (res.data.code === 200) {
                    console.log(res.data);
                    wx.setStorageSync('userInfo', res.data.userInfo);
                    let userInfo = wx.getStorageSync('userInfo')
                    console.log(userInfo)
                    wx.setStorageSync('token', res.data.wxToken);
                    const lastTime = Date.parse(new Date());
                    wx.setStorageSync('lastTime', lastTime);
                    console.log(wx.getStorageSync('userInfo'));
                    if (userInfo.avatarUrl !== 'https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132') {
                      userInfo.avatarUrl = `https://199shq.com/api/common/download?name=${userInfo.avatarUrl}`
                      wx.setStorageSync('userInfo', userInfo);
                      console.log(userInfo);
                    }
                    // 将用户信息存储到页面的数据中
                    that.setData({
                      userInfo: res.data.userInfo,
                    });
                    //将用户信息储存到全局变量中
                    var app = getApp();
                    app.globalData.userInfo = res.data.userInfo;
                    //将用户id储存到userid
                    that.setData({
                      showLoginButton: false,
                      isUserProfileObtained: true,
                    });
                    app.userInfo.showLoginButton = false;
                    wx.hideLoading();
                  }

                },
              });
            },
          });
        } else {
          wx.showModal({
            title: '警告通知',
            content: '您点击了拒绝授权，将无法正常显示个人信息，点击确定重新获取授权。',
            success: function (res) {
              // 用户拒绝登录后的处理
              wx.hideLoading();
            },
          });
        }

      },
    });


  },

  getInputsse: function (e) {
    let ids = 1003
    wx.request({
      url: `https://199shq.com/api/statics/${ids}`, //备注带data这里不需要${addressId} https://199shq.com
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data.announcementId); // 输出存入的数据
        if (res.data.data.typeNumber === 1) {
          wx.navigateTo({
            url: '/pages/bulletinBoard/deatail/deatail?id=' + res.data.data.announcementId
          });

        }
      },
      fail: function (error) {
        console.log(error); // 请求失败的处理
      }
    });
  },
  getInputss: function (e) {
    let ids = 1004
    wx.request({
      url: `https://199shq.com/api/statics/${ids}`, //备注带data这里不需要${addressId} https://199shq.com
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data.announcementId); // 输出存入的数据
        if (res.data.data.typeNumber === 1) {
          wx.navigateTo({
            url: '/pages/bulletinBoard/deatail/deatail?id=' + res.data.data.announcementId
          });

        }
      },
      fail: function (error) {
        console.log(error); // 请求失败的处理
      }
    });
  },
  // 在小程序页面中定义 handleDisagree 方法
  handleDisagree: function () {
    // 在这里编写不同意按钮点击后的处理逻辑

    // 可以执行一些必要的操作，比如关闭弹出窗口或跳转到其他页面

    // 示例：关闭弹出窗口
    this.setData({
      innerShow: false
    });
  },

  //获取轮播图
  getcarousels: function () {
    var that = this;
    wx.request({
      url: 'https://199shq.com/api/carousels',
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data.data);
        var carouselsList = res.data.data;
        console.log(carouselsList)
        if (carouselsList == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            carouselsList: carouselsList
          })
        }
      }
    })
  },


  //onload方法在页面加载完成时开始执行,并且加载数据库数据
  // 获取门店详情数据
  getdata: function () { //定义函数名称
    var that = this;
    wx.request({
      url: 'https://199shq.com/api/stores',
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data);
        var list = res.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            list: res.data
          })
        }
      }
    })
  },
  // 获取静态背景
  getcarous: function () {
    var that = this;

    wx.request({
      url: 'https://199shq.com/api/statics',
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data);
        console.log(res.data.data[0].background);
        var list = res.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: 'toastText',
            icon: '',
            duration: 2000
          });
        } else {
          that.setData({
            img1: res.data.data[0].background,
            img2: res.data.data[1].background,
            img3: res.data.data[2].background,
            img4: res.data.data[3].background
          })
        }
      }
    })
  },

  //
  getInput: function (e) {
    this.setData({
      val: e.detail.value
    })
    if (this.data.val.length > 0) {
      this.setData({
        isSearch: false,
        isCear: true,
      })
    } else {
      this.setData({
        isSearch: true,
        isCear: false,
      })
    }
  },
  //
  cleartap: function () {
    this.setData({
      val: '',
      isSearch: true,
      isCear: false,
    })
  },

  /**头部搜索框部分 */
  getInput() {
    // 判断用户是否已登录
    var userInfo = getApp().globalData.userInfo;
    console.log(userInfo)

    // 判断用户是否已登录

    // 如果用户已授权登录，则跳转到对应页面
    wx.navigateTo({
      url: '../moog/moog',
    });
  },

  //中间小广告部分点击跳转广告

  //点击事件，点击跳转页面
  navigateToDetail: function (event) {
    var id = event.currentTarget.dataset.id; // 获取点击的数据ID

    // 判断用户是否已登录
    var userInfo = getApp().globalData.userInfo;
    console.log(userInfo)

    // 如果用户已授权登录，则跳转到对应页面
    wx.navigateTo({
      url: '../detail/detail?value=' + id,
    });
  },


  //搜索事件定义
  Search: function (event) {
    console.log('回车键被按下了')
    const value = event.detail.value;
    console.log('输入内容：', value);
    //跳转到搜索页面，并且把值传递过去
    wx.navigateTo({
      url: `/pages/search/search?param1=${value}`
    })
  },
  tiao() {
    var userInfo = getApp().globalData.userInfo;
    console.log(userInfo)

    // 判断用户是否已登录
    if (!userInfo) {
      // 如果用户未授权登录，则弹出提示框
      wx.showModal({
        title: '提示',
        content: '请先授权登录账号',
        showCancel: false,
        success: (res) => {
          // 用户点击确定
          if (res.confirm) {
            // 跳转到登录页
            wx.navigateTo({
              url: '../moog/moog',
            });
          }
        }
      });
    } else {
      // 如果用户已授权登录，则跳转到对应页面
      wx.navigateTo({
        url: '../moog/moog',
      });
    }
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }

  },
  //点击触发搜索
  onInput: function () {
    var userInfo = getApp().globalData.userInfo;
    console.log(userInfo)

    // 判断用户是否已登录
    if (!userInfo) {
      // 如果用户未授权登录，则弹出提示框
      wx.showModal({
        title: '提示',
        content: '请先授权登录账号',
        showCancel: false,
        success: (res) => {
          // 用户点击确定
          if (res.confirm) {
            // 跳转到登录页
            const value = this.data.val;
            console.log('输入内容：', value);
            //跳转到搜索页面，并且把值传递过去
            wx.navigateTo({
              url: `/pages/search/search?param1=${value}`
            })
          }
        }
      });
    } else {
      const value = this.data.val;
      console.log('输入内容：', value);
      //跳转到搜索页面，并且把值传递过去
      wx.navigateTo({
        url: `/pages/search/search?param1=${value}`
      })
    }
  },

  //点击获取input内容
  seldata: function (event) {
    const value = event.detail.value;
    console.log(value);
    this.setData({
      val: value,
      Search_del: true
    });
    if (value == '') {
      this.setData({
        Search_del: false
      });
    }
  },

  //点击清空搜索框
  Search_del: function () {
    this.setData({
      val: '',
      Search_del: false
    });
  },

  // tapMe2: function(){
  //   //页面跳转
  //   wx.switchTab({
  //     url: '/pages/detail/detail',
  //   })
  // },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
console.log(options)
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true,
      });
    }

    console.log("监听到当前的页面加载......")
    // 是否获取用户信息，将innerShow设置为false
    var userInfo = wx.getStorageSync('userInfo');

    console.log("userInfo信息是否存在：" + userInfo)
    if (userInfo.wxUserId) {
      this.setData({
        innerShow: false
      })
    } else {
      // wx.redirectTo({
      //   url: `/pages/login/login`
      // })
      this.setData({
        innerShow: false
      })
    }

    //这是参考的代码无用
    //  if (!userInfo) {
    //   var that = this;
    //   wx.showModal({
    //     title: '提示',
    //     content: '是否需要授权登录账号',
    //     showCancel: true, // 为true的时候用户可以取消操作，false的话只能确认
    //     success: function (res) {

    if (options.inviteid != undefined) {
      getApp().globalData.inviteid = options.inviteid;
    }
    this.getdata();
    this.getcarousels();
    this.getcarous();
    if (options.qrcodeId != undefined) {
      wx.request({
        url: `https://199shq.com/api/wxQrCode/${options.qrcodeId}`,
        method: 'GET',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          console.log('jinr')
          console.log(res.data);
          console.log(userInfo.wxUserId);
          if (userInfo.wxUserId != undefined) {
            const data = {
              address: res.data.data.address,
              floorId: res.data.data.floorId,
              departmentId: res.data.data.departmentId,
              courtyardId: res.data.data.courtyardId,
              courtyard:res.data.data.courtyard,
              department: res.data.data.department,
              floor: res.data.data.floor,
              wxUserId: userInfo.wxUserId
            }
            wx.request({
              url: `https://199shq.com/api/wxuserHospitalAddress/save`,
              method: 'POST',
              header: {
                'Content-Type': 'application/json',
                'token': wx.getStorageSync('token')
              },
              data: data,
              success: function (res) {
                console.log('jinr')
                console.log(res.data);
              }
            })
          }

        }
      })
    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {


  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

    // wx.getSetting({
    //   success(res) {
    //     // 检查用户是否已经授权了用户信息
    //     if (res.authSetting['scope.userInfo']) {
    //       console.log('用户已经授权了用户信息')
    //     } else {
    //       console.log('用户没有授权用户信息')
    //     }
    //   }
    // })
    this.getdata();
    this.getcarousels();
    this.getcarous();
    wx.showShareMenu({

      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']

    })
    // Component({
    //   properties: {},
    //   data: {
    //     args: {
    //       withCredentials: true,
    //       lang: 'zh_CN'
    //     }
    //   },
    //   methods: {
    //     loginSuccess: function (res) {
    //       console.log("全局加载时methods下的loginSuccess：" + res.detail);
    //     },
    //     loginFail: function (res) {
    //       console.log("全局加载时methods下的loginFail：" + res);
    //     }
    //   },
    // });


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage:function() {

  //  },
  onShareAppMessage: function (res) {
    return {
      title: '',
      path: '/pages/index/index', // 显示的页面
      imageUrl: "/images/R-C.jpg",
      success: function (res) {
        // 转发成功

        console.log(1)
      },
      fail: function (res) {
        // 转发失败
        console.log(0)
      }
    }
    // }
  },


  onShareTimeline: function (res) {
    return {
      title: 'e膳康',
      path: '/pages/index/index', // 显示的页面
      imageUrl: "/images/R-C.jpg",
      success: function (res) {
        // 转发成功
        console.log(1)
      },
      fail: function (res) {
        // 转发失败
        console.log(0)
      }
    }
  }
})